import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import type { Request } from 'express';
import { User } from '../users/entities/user.entity';
import { roleConstants } from './constants';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor() {}

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    // 获取request
    const req: Request = context.switchToHttp().getRequest<Request>();

    if ((req.user as User)?.role === roleConstants.admin) return true;
    throw new UnauthorizedException(`权限不足`);
  }
}
